/*
 * @Description: 
 * @Author: Jimmy
 * @Date: 2023-07-25 20:10:27
 * @LastEditTime: 2023-07-25 20:18:39
 * @LastEditors:  
 */
import jwt from 'jsonwebtoken';
import { Context, Next } from "koa";
import { config } from '../config/config.default';
import { access } from '../logger';
import { callbackData } from '../utils/data.handler';
import UseService from '../service/user.service'
import { redisGet } from '../utils/redis.client';

//是否登录
export const auth = async (ctx: Context, next: Next) => {
    let { authorization = '' } = ctx.request.header || {};
    const token = authorization?.replace('Bearer ', '') || '';
    try {
        let user:any = jwt.verify(token, config.jwt.secret as string);
        // ctx.state.user = user;
        //从返回结果中剔除password，其他属性放入新的对象中
        const res = await UseService.getUserInfo({ id:user.id})
        if(!res){
            access.error('用户不存在', user)
            console.error('用户不存在')
            ctx.app.emit('error', callbackData('999', '用户不存在'), ctx);
            return false;  
        }else{
            ctx.state.user = res;
        }
        // console.log(await redisGet(`userId_${user.id}`));
    } catch (error) {
        switch(error.name){
            case 'TokenExpiredError':
                access.error('token过期', error)
                console.error('token过期', error)
                ctx.app.emit('error', callbackData('999', 'token过期'), ctx);
                return false;
            case 'JsonWebTokenError':
                access.error('无效的token', error)
                console.error('无效的token')
                ctx.app.emit('error', callbackData('999', '无效的token'), ctx);
                return false;
            default:
                access.error('token不存在', error)
                console.error('token不存在')
                ctx.app.emit('error', callbackData('999', 'token不存在'), ctx);
                return false;
        }
    }
    await next();
}

//是否管理员
export const hadAdminPermission = async(ctx,next)=>{
    const  {is_admin} = ctx.state.user;
    if(!is_admin){
        console.error('无操作权限')
        ctx.app.emit('error', callbackData('1', '无操作权限'), ctx);
        return false;
    }
    await next();
}